package com.suma.platform.core.util;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author suma
 * @date 2018/2/6 上午9:36
 */
public class Queue<T> {
	private Object[] elements;
	private Lock lock = new ReentrantLock();
	private Condition notEmpty = lock.newCondition();
	private Condition notFull = lock.newCondition();
	private int length = 0;
	private int addIndex = 0;
	private int removeIndex = 0;

	public Queue(int size) {
		elements = new Object[size];
	}

	public void add(T object) throws InterruptedException {
		lock.lock();
		try {
			while (length == elements.length) {
				System.out.println("队列已满");
				notFull.await();
			}
			elements[addIndex] = object;
			if (addIndex++ == elements.length) {
				addIndex = 0;
			}
			length++;
			notEmpty.signal();
		} finally {
			lock.unlock();
		}
	}

	public T remove() throws InterruptedException {
		lock.lock();
		try {
			while (0 == length) {
				System.out.println("队列为空");
				notEmpty.await();
			}
			Object element = elements[removeIndex];
			if (removeIndex++ == elements.length) {
				removeIndex = 0;
			}
			length--;
			notFull.signal();
			return (T) element;
		} finally {
			lock.unlock();
		}
	}
}
